package com.aweqy.subjectredis.config;

import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

@Service
public class RedisKeyService {

    private final StringRedisTemplate stringRedisTemplate;

    public RedisKeyService(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public Set<String> getSubjectCategoryKeys(String key) {
        ScanOptions options = ScanOptions.scanOptions()
                .match(key)
                .build();

        return stringRedisTemplate.execute(connection -> {
            Set<String> keys = new HashSet<>();
            Cursor<byte[]> cursor = connection.scan(options);
            while (cursor.hasNext()) {
                keys.add(new String(cursor.next()));
            }
            return keys;
        }, true);
    }

    public Set<String> getSubjectCategoryKeysExcludingCounters(String key) {
        // 1. 构建扫描选项，匹配所有非 counter 的键
        ScanOptions options = ScanOptions.scanOptions()
                .match(key) // 原始匹配模式（如 "subject:category:*"）
                .build();

        return stringRedisTemplate.execute(connection -> {
            Set<String> keys = new HashSet<>();
            Cursor<byte[]> cursor = connection.scan(options);

            while (cursor.hasNext()) {
                String redisKey = new String(cursor.next());
                // 2. 手动检查是否包含 "counter"
                if (!redisKey.contains("counter")) {
                    keys.add(redisKey);
                }
            }
            return keys;
        }, true);
    }
}